<script lang="ts" setup>
import useLoading from '@/hooks/loading'
import type { FormInstance } from '@arco-design/web-vue/es/form'
import { TitleMap } from '@/config/constants'
import request from '@/utils/request'
import { set } from '@vueuse/core'
import { cloneDeep } from 'lodash'

interface EditProps {
  modelForm: any
  editVisible: boolean
  createData: any
  updateData: any
  title?: string
  dialogStatus: string
  setEditVisible: any
}

const props = withDefaults(defineProps<EditProps>(), {
  editVisible: false,
  modelForm: {
    sex: 1,
    ord: 0,
    status: 1,
    title: '',
    content: '',
  },
  dialogStatus: 'create',
  createData: () => {},
  updateData: () => {},
  setEditVisible: () => {},
})
const { modelForm } = toRefs(props)
const { loading, setLoading } = useLoading()
const formRef = ref<FormInstance>()
const roleOptions = ref<any>([])
const roles = ref<any>([])

request.get('/role').then((res) => {
  set(roleOptions, res.rows)
})

const handleClose = () => {
  props.setEditVisible()
  formRef.value!.resetFields()
  set(roles, [])
}

const handleRoles = (checked: any) => {
  // const selectedRoles = roleOptions.value.filter((t: any) => checked.includes(t.id))
  const selectedRoles = roleOptions.value.filter((t: any) => checked === t.id)
  const roles = selectedRoles.map((item: any) => ({ userId: modelForm.value.id, name: item.name, id: item.id }))
  modelForm.value.roles = roles
}

const onChangeRole = (value: any) => {
  set(roles, value)
  handleRoles(value)
}

// 发布
const handleSubmit = () => {
  formRef
    .value!.validate((valid: any) => {
      if (valid) return

      const data = cloneDeep(unref(modelForm))

      data.status = typeof data.status !== 'undefined' ? +data.status : 1
      props.dialogStatus === 'create' ? props.createData(data) : props.updateData(data)

      handleClose()
    })
    .catch((error: any) => {
      console.log('error', error)
    })
    .finally(() => {
      setLoading(false)
    })
}

// 修改时角色选中
watch(
  () => props.modelForm,
  (val) => {
    if (val && Array.isArray(val.roles)) {
      roles.value = val.roles?.map((t: any) => t.id)
    }
  },
  { deep: true, immediate: true }
)

const visible = ref(false)
watch(
  () => props.editVisible,
  (show) => {
    visible.value = show
  }
)
</script>
<template>
  <a-modal v-model:visible="visible" @ok="handleSubmit" @cancel="handleClose" draggable :width="650" :loading="loading">
    <template #title>{{ TitleMap[dialogStatus] }}</template>
    <a-alert hidden title="文明发言" type="warning" class="mb-5" :closable="true" />
    <a-form ref="formRef" :model="modelForm" auto-label-width>
      <a-form-item field="id" hidden>
        <input type="hidden" name="id" :value="modelForm.id" />
      </a-form-item>

      <a-row :gutter="20">
        <a-col :span="12">
          <a-form-item label="用户名" field="username">
            <a-input v-model.trim="modelForm.username" placeholder="请输入用户名" />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="用户密码" field="password">
            <a-input-password v-model.trim="modelForm.password" placeholder="请输入用户密码" allow-clear />
          </a-form-item>
        </a-col>
      </a-row>

      <a-row :gutter="20">
        <a-col :span="12">
          <a-form-item label="用户昵称" field="nickName">
            <a-input v-model.trim="modelForm.nickName" placeholder="请输入用户昵称" />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="手机号码" field="phone">
            <a-input v-model.trim="modelForm.phone" :max-length="11" placeholder="请输入手机号码" />
          </a-form-item>
        </a-col>
      </a-row>

      <a-row :gutter="20">
        <a-col :span="12">
          <a-form-item label="性别" field="sex">
            <a-radio-group v-model="modelForm.sex">
              <a-radio :value="1">男</a-radio>
              <a-radio :value="2">女</a-radio>
            </a-radio-group>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="状态" field="status">
            <a-radio-group v-model="modelForm.status">
              <a-radio :value="1">正常</a-radio>
              <a-radio :value="2">禁用</a-radio>
            </a-radio-group>
          </a-form-item>
        </a-col>
      </a-row>

      <a-form-item label="角色" field="roles" :rules="[{ required: true, message: '请选择角色' }]" :validate-trigger="['change', 'blur']">
        <a-select v-model="roles" placeholder="请选择角色" @change="onChangeRole">
          <a-option v-for="item in roleOptions" :key="item.id" :label="item.name" :value="item.id" />
        </a-select>
      </a-form-item>
      <a-form-item label="备注" field="remark">
        <a-textarea v-model="modelForm.remark" :row="4" :max-length="100" allow-clear show-word-limit auto-size />
      </a-form-item>
    </a-form>
  </a-modal>
</template>
<style lang="scss"></style>
